//
//  XLOrderViewController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2018/1/25.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLOrderViewController.h"
#import "XLOrderTableViewCell.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import <ReactiveCocoa.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <ImSDK/ImSDK.h>
#import "IMAMsg.h"
#import <ImSDK/ImSDK.h>
 
#import "XLHTTPSessionManager+Analytics.h"

@interface XLOrderViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, weak) RACDisposable *observerDisposable;
@property (nonatomic, weak) RACDisposable *observerDisposable1;
@property (nonatomic, weak) RACDisposable *requestDisposable;
@property (nonatomic, strong) NSDictionary *dic;
@property (nonatomic, weak) NSTimer *timer;
@property (nonatomic, assign) BOOL shouldRefresh;
@property (nonatomic, assign) NSInteger errCount;
@end

@implementation XLOrderViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_interactivePopDisabled = YES;
    self.userId = [[XLAccountManager shareInstance] model].Id;
    self.errCount = 0;
    
    [self setupView];
    [MBProgressHUD showMessage:@"" toView:self.view];
    [self requestOrderList];
    [self addObserver];
    [self joinGroup];
    
    [self analyticsEvent1];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setupTimer];
}

- (void)dealloc {
    [self.observerDisposable dispose];
    [self.observerDisposable1 dispose];
    [self.requestDisposable dispose];
}

- (void)setupTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)timerAction {
    if (self.shouldRefresh) {
        [self requestOrderList];
        self.shouldRefresh = NO;
    }
}

- (void)addObserver {
    @weakify(self);
    self.observerDisposable = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"JoinOrderRefresh" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        self.shouldRefresh = YES;
    }];
    self.observerDisposable1 = [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"QuitOrderRefresh" object:nil] subscribeNext:^(NSNotification *notification) {
        @strongify(self);
        NSString *userId = notification.object;
        NSDictionary *d;
        for (NSDictionary *dic in self.dataArray) {
            NSString *receiver = F(@"%@", dic[@"UserId"]);
            if ([receiver isEqualToString:userId]) {
                d = dic;
                break;
            }
        }
        if (d) {
            NSMutableArray *temp = self.dataArray.mutableCopy;
            [temp removeObject:d];
            self.dataArray = temp.copy;
            [self.tableView reloadData];
        }
    }];
}

- (void)setupView {
    self.navigationItem.title = @"抢单大厅";
    [self showBackButton:NULL];
    
    UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [refreshButton setImage:[UIImage imageNamed:@"supei_nav_but_shuaxin_n"] forState:UIControlStateNormal];
    [refreshButton addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshButton];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 86;
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = [UIView new];
    [_tableView registerClass:[XLOrderTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XLOrderTableViewCell class])];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)requestOrderList {
    [self.requestDisposable dispose];
    self.requestDisposable = [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:self.userId] subscribeNext:^(id x) {
        self.errCount = 0;
        [MBProgressHUD hideHUDForView:self.view];
//        "UserId": 448859,
//        "ImgUrl": "http://p001.baomihua.com/345958f7-6120-43fb-8b72-fca3b4b2326b.jpg",
//        "NickName": "test栋",
//        "MatchId": "55b90900543b4796a9e70f7acba325be"
        self.dataArray = x;
        [self.tableView reloadData];
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (self.errCount <= 5) {
            self.errCount++;
            [self requestOrderList];
        } else {
            [MBProgressHUD showContent:@"获取订单列表失败，请稍后再试" toView:self.view];
        }
    }];
}

- (void)joinGroup {
    [[TIMGroupManager sharedInstance] JoinGroup:@"10086" msg:@"" succ:^{
        [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
        } fail:^(int code, NSString *msg) {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    } fail:^(int code, NSString *msg) {
        if (code == 10013) {
            [[TIMGroupManager sharedInstance] ModifyGroupMemberInfoSetNameCard:@"10086" user:[[XLAccountManager shareInstance] model].Id nameCard:@"1" succ:^{
            } fail:^(int code, NSString *msg) {
                [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }];
        } else {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

- (void)refreshAction {
    [self requestOrderList];
}

- (void)sendCustomMessageOrder:(NSDictionary *)dic {
    TIMMessage *msg = [[TIMMessage alloc] init];
    TIMOfflinePushInfo *info = [[TIMOfflinePushInfo alloc] init];
    info.pushFlag = TIM_OFFLINE_PUSH_NO_PUSH;
    [msg setOfflinePushInfo:info];
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    NSDictionary *d = @{
                        @"oppositeUserId" : dic[@"UserId"],
                        @"orderNum":dic[@"MatchId"],
                        @"name" : [[XLAccountManager shareInstance] model].NickName,
                        @"headimg" : [[XLAccountManager shareInstance] model].HeadImg,
                        @"leval" : @"1",
                        @"levalIcon" : @"",
                        @"address" : [[XLAccountManager shareInstance] model].HostCity,
                        @"age" : @([[XLAccountManager shareInstance] model].Age),
                        @"job" : @""
                        };
    elem.data = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
    elem.desc = @"QiangDanNotification";
    elem.ext = @"QiangDanNotification";
    [msg addElem:elem];
    NSString *receiver = F(@"%@", dic[@"UserId"]);
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:receiver];
    [con sendMessage:msg succ:^{

    } fail:^(int code, NSString *msg) {

    }];

}

- (void)grabOrder:(NSDictionary *)dic {
    [MBProgressHUD showContent:@"" toView:self.view];
    [[[XLHTTPSessionManager sharedManager] grabOrderWithUserId:dic[@"UserId"] anchorId:self.userId matchId:dic[@"MatchId"]] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self requestOrderList];
        });
        NSInteger result = [x[@"result"] integerValue];
        if (result == 0) { //抢单成功，发送自定义消息
            [self sendCustomMessageOrder:(NSDictionary *)dic];
        } else if (result == -10001 || result == -10003) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你手慢了" message:@"该用户已经被其他美女抢走了，看看其他用户吧" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:NULL];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:@"该用户已经被其他美女抢走了，看看其他用户吧" attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            [alert setValue:atr forKey:@"attributedMessage"];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:NULL];
        } else if (result == -10002) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"用户已取消通话" message:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" preferredStyle:UIAlertControllerStyleAlert];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            [alert setValue:atr forKey:@"attributedMessage"];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:NULL];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"邀请他" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:F(@"%@", dic[@"UserId"])];
                NSDictionary * xmlDic = @{
                                          @"action": @8,
                                          @"imageUrl": [[XLAccountManager shareInstance] model].HeadImg ?: @"",
                                          };
                IMAMsg *msg = [IMAMsg shareToGroupMsgWithCustomDic:xmlDic];
                [conversation sendMessage:msg completion:^(NSArray *imamsglist, BOOL succ, int code) {
                    
                }];
            }];
            [alert addAction:action1];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:NULL];
        } else {
            [MBProgressHUD showContent:x[@"msg"] toView:self.view];
        }
        
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:@"抢单失败" toView:self.view];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XLOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLOrderTableViewCell class]) forIndexPath:indexPath];
    NSDictionary *dic = self.dataArray[indexPath.row];
    [cell.avatarView setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
    cell.nameLabel.text = dic[@"NickName"];
    @weakify(self);
    cell.grabBlock = ^{
        @strongify(self);
        self.dic = dic;
        [self grabOrder:dic];
        [self analyticsEvent2];
    };
    return cell;
}
#pragma mark - analyticsEvent
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"camgirlid"];
    }
    if (self.dic[@"UserId"]) {
        [attributes setObject:self.dic[@"UserId"] ?: @"" forKey:@"userid"];
    }
    return attributes.copy;
}

- (void)analyticsEvent1 {//进入老用户首页
    NSDictionary *attributes = [self genrateAttributes];
    [MobClick event:@"xl_oldindex" attributes:attributes];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_calllist" action:@"xl_calllist" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}

- (void)analyticsEvent2 {//进入老用户首页
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_oldindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_calllist" action:@"xl_clickgrab" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}


@end
